﻿using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

namespace MuscleFellow.API.JWT
{
    public class TokenEntity
    {
        public string access_token { get; set; }
        public int expires_in { get; set; }   
    }
    public class TokenProvider
    {
        private readonly TokenProviderOption _tokenProviderOption;

        public TokenProvider(TokenProviderOption tokenProviderOption)
        {
            _tokenProviderOption = tokenProviderOption;
        }

        public async Task<TokenEntity> GenerateToken(HttpContext context, string userName, string password)
        {
            var identity = await GetIdentity(userName);
            if (identity==null)
            {
                return null;
            }
            var now = DateTime.UtcNow;
            var claims = new Claim[]
            {
                new Claim(JwtRegisteredClaimNames.Sub,userName),
                new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString()), 
                new Claim(JwtRegisteredClaimNames.Iat,ToUnixEpochDate(now).ToString(),ClaimValueTypes.Integer64), 
            };
            //创建Token并把它写到字符串中
            var jwt = new JwtSecurityToken(
                issuer:_tokenProviderOption.Issuer,
                audience:_tokenProviderOption.Audience,
                claims:claims,
                notBefore:now,
                expires:now.Add(_tokenProviderOption.Expiration),
                signingCredentials:_tokenProviderOption.SigningCredentials
            );
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
            var response = new TokenEntity
            {
                access_token = encodedJwt,
                expires_in = (int)_tokenProviderOption.Expiration.TotalSeconds
            };
            return response;
        }

        private long ToUnixEpochDate(DateTime datetime)
        {
            return (long)Math.Round((datetime.ToUniversalTime()-new DateTimeOffset(1970,1,1,0,0,0,TimeSpan.Zero)).TotalSeconds);
        }

        private Task<ClaimsIdentity> GetIdentity(string userName)
        {
            throw new System.NotImplementedException();
        }
    }
}